package com.tjcd.project.library_base.common.upload.net;


import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.tjcd.project.library_base.base.bean.BaseResponseBean;
import com.tjcd.project.library_base.common.upload.net.interf.NetBeanListener;

import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;


/**
 * @Author junweiliu
 * @Description 基础Observer
 * @Version 1.0
 * @CreateDate 2019/12/23
 * @QQ 1007271386
 */
public abstract class BaseFileObserver<T extends BaseResponseBean> implements Observer<T>, NetBeanListener<T> {
    /**
     * 错误信息
     */
    protected String errMsg = "";
    /**
     * disposable
     */
    protected Disposable mDisponable;

    @Override
    public void onSubscribe(Disposable d) {
        onLoadStart();
        mDisponable = d;
    }

    @Override
    public void onNext(T t) {
//        LogUtils.e("请求结果:" + GsonUtils.toJson(t));
        onLoadFinished();
        if (null != t && "200".equals(t.getCode()) || "0".equals(t.getCode())) { // 如果返回码是0 表示成功 正常应该是200才对 - -!
            onSuc(t);
        } else {
//            onFail("响应错误~");
            if (null != t && !TextUtils.isEmpty(t.getMsg())){
                onFail(t.getMsg());
            } else{
                onFail("响应错误~");
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        LogUtils.e("请求异常:" + e.toString());
        if (!NetworkUtils.isConnected()
                || e instanceof SocketTimeoutException
                || e instanceof SocketException
                || e instanceof UnknownHostException) { // 网络连接失败
            errMsg = "网络连接错误~";
        } else if (e instanceof HttpException) { // 网络请求失败
//            ResponseBody body = ((HttpException) e).response().errorBody();
            errMsg = "网络异常错误~";
        } else { // 其他错误
            errMsg = "系统异常错误~";
        }
        onLoadFinished();
        onFail(errMsg);
    }

    @Override
    public void onComplete() {
    }

    /**
     * 请求开始时的处理
     * 如果需要处理一些操作,重写该方法
     */
    @Override
    public void onLoadStart() {

    }

    /**
     * 请求结束时的处理
     * 如果需要处理一些操作,重写该方法
     */
    @Override
    public void onLoadFinished() {

    }

    /**
     * 销毁
     */
    protected void dispose() {
        if (null != mDisponable && !mDisponable.isDisposed()) {
            mDisponable.dispose();
        }
    }
}
